'use strict'

import Vue from 'vue'
import axios from 'axios'

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || ''
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

let config = {
  baseURL: process.env.baseURL || process.env.apiUrl || '',
  timeout: 5 * 1000, // Timeout
  withCredentials: true // Check cross-site Access-Control
}

// 创建一个 axios 实例
const _axios = axios.create(config)

// axios 请求拦截器
_axios.interceptors.request.use(
  config => {
    // 在请求之前的处理
    // 将在请求接口之前添加token到header
    const token = window.sessionStorage.getItem('token')
    config.headers['Token'] = token
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// axios 响应拦截器
_axios.interceptors.response.use(
  response => {
    // 处理响应中的数据
    const resData = response.data
    const { code } = resData
    switch (code) {
      case 0:
        // code === 0 代表无错误
        return resData
      // todo 设置更多的code值定义
      default:
        // 非正确 code
        throw new Error('msg')
    }
  },
  error => {
    if (error && error.response) {
      // 根据状态码判断错误类型
      switch (error.response.status) {
        case 400: error.message = '请求错误'; break
        case 401: error.message = '未授权，请登录'; break
        case 403: error.message = '拒绝访问'; break
        case 404: error.message = `请求地址出错: ${error.response.config.url}`; break
        case 408: error.message = '请求超时'; break
        case 500: error.message = '服务器内部错误'; break
        case 501: error.message = '服务未实现'; break
        case 502: error.message = '网关错误'; break
        case 503: error.message = '服务不可用'; break
        case 504: error.message = '网关超时'; break
        case 505: error.message = 'HTTP版本不受支持'; break
        default: break
      }
      return Promise.reject(error)
    }
  }
)

Plugin.install = function (Vue, options) {
  Vue.axios = _axios
  window.axios = _axios
  Object.defineProperties(Vue.prototype, {
    axios: {
      get () {
        return _axios
      }
    },
    $axios: {
      get () {
        return _axios
      }
    }
  })
}

Vue.use(Plugin)

export default Plugin
